<template>
  <div class="outbound-order-container">
    <!-- 创建订单按钮 -->
    <div class="action-bar">
      <el-button type="primary" @click="createDialogVisible = true">创建出库订单</el-button>
    </div>

    <!-- 出库订单列表 -->
    <el-table 
      :data="currentPageData" 
      border 
      stripe 
      fit 
      style="width: 100%; margin-top: 20px"
    >
      <el-table-column prop="_id" label="订单ID" min-width="220" show-overflow-tooltip />
      <el-table-column prop="productName" label="商品名称" min-width="180" />
      <el-table-column prop="quantity" label="出库数量" width="120" align="center" />
      <el-table-column prop="userName" label="收货人" min-width="120" />
      <el-table-column prop="phone" label="联系电话" min-width="150" />
      <el-table-column prop="address" label="收货地址" min-width="200" show-overflow-tooltip />
      <el-table-column prop="status" label="订单状态" width="150" align="center">
        <template #default="scope">
          <el-tag :type="getStatusTagType(scope.row.status)">
            {{ scope.row.status }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="createdAt" label="创建时间" width="200" align="center">
        <template #default="scope">
          {{ formatTime(scope.row.createdAt) }}
        </template>
      </el-table-column>
      <el-table-column label="操作" width="200" align="center">
        <template #default="scope">
          <!-- 待审核状态：显示审核按钮 -->
          <el-button 
            v-if="scope.row.status === '待审核'" 
            type="info" 
            size="small"
            @click="showAuditDialog(scope.row._id)"
          >审核</el-button>

          <!-- 待发货审核状态：显示发货按钮 -->
          <el-button 
            v-if="scope.row.status === '待发货审核'" 
            type="success" 
            size="small"
            @click="handleDeliver(scope.row._id)"
          >发货</el-button>

          <!-- 审核不通过状态：显示重新审核按钮 -->
          <el-button 
            v-if="scope.row.status === '审核不通过'" 
            type="primary" 
            size="small"
            @click="handleReAudit(scope.row._id)"
          >重新审核</el-button>
          <!-- 查看详情按钮 -->
          <el-button type="text" size="small" @click="handleViewDetail(scope.row._id)">查看详情</el-button>
        </template>
      </el-table-column>
    </el-table>
    <div class="pagination-container">
    <el-pagination
      :current-page="currentPage"
      :page-size="pageSize"
      :total="total"
      layout="prev, pager, next, jumper, ->, total"
      @current-change="handleCurrentChange"
      style="margin-top: 20px;"
    />
  </div>

    <!-- 创建订单对话框 -->
    <el-dialog 
      title="创建出库订单" 
      v-model="createDialogVisible"
      width="50%"
    >
      <el-form ref="createFormRef" :model="createForm" :rules="createRules" label-width="100px">
        <el-form-item label="商品ID" prop="productId">
          <el-input v-model="createForm.productId" placeholder="请输入商品MongoDB ID" />
        </el-form-item>
        <el-form-item label="商品名称" prop="productName">
          <el-input v-model="createForm.productName" placeholder="请输入商品名称" />
        </el-form-item>
        <el-form-item label="出库数量" prop="quantity">
          <el-input-number v-model="createForm.quantity" min="1" placeholder="请输入出库数量" />
        </el-form-item>
        <el-form-item label="收货人" prop="userName">
          <el-input v-model="createForm.userName" placeholder="请输入收货人姓名" />
        </el-form-item>
        <el-form-item label="联系电话" prop="phone">
          <el-input v-model="createForm.phone" placeholder="请输入联系电话" />
        </el-form-item>
        <el-form-item label="收货地址" prop="address">
          <el-input v-model="createForm.address" placeholder="请输入收货地址" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="createDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleCreate">提交</el-button>
      </template>
    </el-dialog>

    <!-- 审核对话框 -->
    <el-dialog 
      title="审核出库订单" 
      v-model="auditDialogVisible"
      width="30%"
    >
      <p>请选择审核结果：</p>
      <template #footer>
        <div style="display: flex; justify-content: space-between; width: 100%;">   
        <el-button type="danger" @click="handleRejectAudit(currentOrderId)">不通过</el-button>
        <el-button type="success" @click="handleApproveAudit(currentOrderId)">通过</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed} from 'vue'
import { ElMessage } from 'element-plus'
import { logisticsApi } from '@/api/logistics'
import dayjs from 'dayjs'
import { useRouter } from 'vue-router'
const router = useRouter()
const handleViewDetail = (id) => {
    //跳转 到详情页面
    router.push({ path: `/outOrderDetail/${id}` })
}
// 出库订单列表数据
const outboundOrders = ref([])

// 创建订单相关
const createDialogVisible = ref(false)
const createForm = reactive({
  productId: '',
  productName: '',
  quantity: 1,
  userName: '',
  phone: '',
  address: ''
})
const createRules = {
  productId: [{ required: true, message: '请输入商品ID', trigger: 'blur' }],
  productName: [{ required: true, message: '请输入商品名称', trigger: 'blur' }],
  quantity: [{ required: true, message: '请输入出库数量', trigger: 'blur' }],
  userName: [{ required: true, message: '请输入收货人姓名', trigger: 'blur' }],
  phone: [{ required: true, message: '请输入联系电话', trigger: 'blur' }],
  address: [{ required: true, message: '请输入收货地址', trigger: 'blur' }]
}
const createFormRef = ref(null)

// 审核相关
const auditDialogVisible = ref(false)
const currentOrderId = ref('')

// 初始化加载订单列表
onMounted(async () => {
  await fetchOutboundOrders()
})
// 新增分页状态
const currentPage = ref(1)  // 当前页（初始为1）
const pageSize = ref(10)    // 每页显示10条（固定值）
const total = ref(0)        // 总数据量（等于purchaseOrders长度）

// 计算当前页展示的数据（关键）
const currentPageData = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value
  const end = start + pageSize.value
  return outboundOrders.value.slice(start, end)
})

// 获取出库订单列表
const fetchOutboundOrders = async () => {
  try {
    const res = await logisticsApi.getOutboundOrdersList()
    outboundOrders.value = res
    total.value = res.length  // 总数据量等于数组长度
  } catch (err) {
    ElMessage.error(err.response?.data?.message || '获取出库订单列表失败')
  }
}

// 处理创建订单
const handleCreate = async () => {
  await createFormRef.value.validate(async (valid) => {
    if (!valid) return
    try {
      await logisticsApi.createOutboundOrder(createForm)
      ElMessage.success('出库订单创建成功')
      createDialogVisible.value = false
      createFormRef.value.resetFields()
      await fetchOutboundOrders() // 刷新列表
    } catch (err) {
      ElMessage.error(err.response?.data?.message || '创建出库订单失败')
    }
  })
}

// 显示审核对话框
const showAuditDialog = (id) => {
  currentOrderId.value = id
  auditDialogVisible.value = true
}

// 审核通过
const handleApproveAudit = async (id) => {
  try {
    await logisticsApi.approveOutboundOrder(id)
    ElMessage.success('出库订单审核通过')
    auditDialogVisible.value = false
    await fetchOutboundOrders() // 刷新列表
  } catch (err) {
    ElMessage.error(err.response?.data?.message || '审核通过失败')
  }
}

// 审核不通过
const handleRejectAudit = async (id) => {
  try {
    await logisticsApi.rejectOutboundOrder(id)
    ElMessage.success('出库订单审核不通过')
    auditDialogVisible.value = false
    await fetchOutboundOrders() // 刷新列表
  } catch (err) {
    ElMessage.error(err.response?.data?.message || '审核不通过失败')
  }
}

// 处理发货操作
const handleDeliver = async (id) => {
  try {
    await logisticsApi.deliverOutboundOrder(id)
    ElMessage.success('出库订单发货成功')
    await fetchOutboundOrders() // 刷新列表
  } catch (err) {
    ElMessage.error(err.response?.data?.message || '发货失败')
  }
}

// 处理重新审核
const handleReAudit = async (id) => {
  try {
    await logisticsApi.reAuditOutboundOrder(id)
    ElMessage.success('出库订单重新提交审核成功')
    await fetchOutboundOrders() // 刷新列表
  } catch (err) {
    ElMessage.error(err.response?.data?.message || '重新审核失败')
  }
}

// 状态标签颜色映射
const getStatusTagType = (status) => {
  const map = {
    '待审核': 'info',
    '待发货审核': 'warning',
    '审核不通过': 'danger',
    '已发货': 'success'
  }
  return map[status] || 'default'
}

// 时间格式化
const formatTime = (time) => {
  return dayjs(time).format('YYYY-MM-DD HH:mm:ss')
}
</script>

<style scoped>
.outbound-order-container {
  padding: 20px;
}

.action-bar {
  margin-bottom: 20px;
}

.el-table .el-button {
  margin: 0 5px;
}
.pagination-container {
  display: flex;
  justify-content: center; /* 水平居中 */
  align-items: center; /* 垂直居中 */
  text-align: center; /* 水平居中 */
  margin: 20px 0; /* 调整上下边距 */
}

/* 可选：调整分页组件内间距 */
.el-pagination {
  padding: 10px 20px; /* 增加内边距使组件更饱满 */
}
</style>